#!/bin/bash

umask 0077
# 返回码
declare -i ret_ok=0                                 # 成功
declare -i ret_upgrade_failed=1                     # 升级失败
declare -i ret_upgrade_ok_need_restart=2            # 需要升级 需要重启
declare -i ret_failed_dictionary_no_space=3         # 失败 文件夹空间不够
declare -i ret_process_runing_exit=4                # 进程正在运行，退出
declare -i ret_no_satisfy_upgrade_condition=5       # 当前环境不满足 退出 不删除升级包
declare -i ret_failed_copy_file_failed=6            # 失败 拷贝文件失败
declare -i ret_backup_finish_restart=7             # exec backup file restart
declare -i ret_failed_upgrade_mode_exit=8           # 失败 升级模式 退出
declare -i ret_failed_set_upgrade_process_failed=9  # set upgrade process file failed

declare -i ret_no_need_upgrade=10                  # 当前未找到升级包
declare -i ret_effect_ha_failed=11                  # effect ha failed after reboot
declare -i ret_set_edge_effect_flag_fail=12         # set edge effect flag fail after reboot
declare -i ret_effect_restart=13                    # exec effect restart
declare -i ret_invalid_user=14
source /etc/profile 2>/dev/null
unset http_proxy https_proxy ftp_proxy HTTP_PROXY HTTPS_PROXY FTP_PROXY
PYTHON3=$(type -p python3)

path=$(cd $(dirname $0); pwd)
cd ${path}
#工作目录默认当前目录
WORK_PATH=${path}

# 默认设备名称
DEFAULT_PRODUCT_NAME="Atlas 200"
# 默认设备名称
DEFAULT_PRODUCT_TYPE="Atlas 200"
# define atlas 500 board type
ATLAS500_BOARD_TYPE="sei"

# config file
ATLASEDGE_CONFIG_FILE="${WORK_PATH}/config/config.ini"
#site程序
ATLASEDGE_SITE_BIN=${WORK_PATH}/software/edge_site/postern_main.py
#sudo site程序
SUDO_ATLASEDGE_SITE_BIN="sudo -b ${PYTHON3} ${ATLASEDGE_SITE_BIN}"
#core程序
ATLASEDGE_CORE_BIN=${WORK_PATH}/software/edge_core/edge_core

LOG_PATH=""

# 保活轮训监控时间
ATLASEDGE_WATCHDOG_SECOND=5

SITE_SCRIPT_DIR="software/edge_site/edge_manager/src/script"
SCRIPT_PATH=${WORK_PATH}/${SITE_SCRIPT_DIR}
SITE_PYTHON_PATH="${WORK_PATH}/software/edge_site/edge_manager/src/python"
CORE_CONFIG_FILE="software/edge_core/conf/edgecore.yaml"
EDGE_WORK_DIR="/opt/middleware"

# import log and common function
. ${SCRIPT_PATH}/log_util.sh
. ${SCRIPT_PATH}/common.sh

check_upgrade_running()
{
    if [ ! -f ${WORK_PATH}/upgrade.pid ];then
        return 0
    fi

    upgrade_pid=`cat ${WORK_PATH}/upgrade.pid`

    if ! [ -n "$upgrade_pid" -a -e /proc/$upgrade_pid ]; then
        logger_Warn "AtlasEdge upgrade pid:$upgrade_pid not exist rm"
        rm ${WORK_PATH}/upgrade.pid
        return 0
    fi

    return 1
}

# 检测主进程是否正在运行
checkEdgeIsRunning() {
    # upgrade process continue
    if  [ $# == 1 -a "$1" == "upgrade" ]; then
        logger_Info "AtlasEdge upgrade process go on"
    else
        # check is another program runing
        OtherPid=$(pidof -o $$ -x *edge_main.sh)
        if [ "$OtherPid" != "" ];then
            logger_Warn "AtlasEdge another:${OtherPid} runing so exit"
            return $ret_process_runing_exit
        fi

        check_upgrade_running
        ret=$?
        if [ $ret == 1 ];then
            logger_Warn "AtlasEdge upgrade mode so exit"
            return $ret_failed_upgrade_mode_exit
        fi

    fi

    return 0
}

function check_and_copy_encrypt() {
    if [[ ! -f /home/data/config/main/config/work/.default1.enc ]] && [[ ! -f /home/data/config/bak/config/work/.default1.enc ]]; then
        logger_Info "start copy encrypt file"
        sudo mkdir -p /home/data/config/main/config/work
        sudo mkdir -p /home/data/config/bak/config/work
        sudo cp -f /home/data/config/main/config/work/.baseMcsCert.enc /home/data/config/main/config/work/.default1.enc
        sudo cp -f /home/data/config/main/config/work/.baseMcsCert.enc /home/data/config/bak/config/work/.default1.enc
        sudo cp -f /home/data/config/main/config/work/.userMcsCert.enc /home/data/config/main/config/work/.default2.enc
        sudo cp -f /home/data/config/main/config/work/.userMcsCert.enc /home/data/config/bak/config/work/.default2.enc
        sudo cp -f /home/data/config/main/config/work/.ipc.enc /home/data/config/main/config/work/.default3.enc
        sudo cp -f /home/data/config/main/config/work/.ipc.enc /home/data/config/bak/config/work/.default3.enc
    fi
}

# 设置基准环境变量和动态库链接
set_bin_path_environment(){
    export PYTHONPATH=$PYTHONPATH:${WORK_PATH}/software/edge_site/opensource:${WORK_PATH}/software/edge_site
    export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${WORK_PATH}/software/lib/
    export ATLASEDGE_WORK_PATH=${WORK_PATH}
    export ATLASEDGE_CONFIG_PATH=${WORK_PATH}/config
    export ATLASEDGE_SOFTWARE_PATH=${WORK_PATH}/software

    if [ ! -f ${WORK_PATH}/config/modelfiles.json ]; then
        echo {} | sudo tee ${WORK_PATH}/config/modelfiles.json > /dev/null
        sudo chmod 644 ${WORK_PATH}/config/modelfiles.json
    fi
    if [ ! -f ${WORK_PATH}/config/user_set_capablity.json ]; then
        echo {} | sudo tee ${WORK_PATH}/config/user_set_capablity.json > /dev/null
        sudo chmod 644 ${WORK_PATH}/config/user_set_capablity.json
    fi

    check_and_copy_encrypt

    return 0
}

exec_ha_status_monitor()
{
    if [ $1 == "stop" ]; then
        for ps in $(ps -ww -eo pid,cmd | grep -v grep | grep -w ${SCRIPT_PATH}/ha_status_monitor.sh | awk '{print $1}'); do
            kill -9 $ps
        done
    elif [ $1 == "start" ]; then
        ${SCRIPT_PATH}/ha_status_monitor.sh &
        ha_monitor_pid=$(ps -ww -eo pid,cmd | grep -v grep | grep -w ${SCRIPT_PATH}/ha_status_monitor.sh | awk '{print $1}' | tail -n1)
        logger_Info "start ha status monitor process pid: $ha_monitor_pid"
    fi
}

exec_mod_backup_process(){
    if [ $1 == "stop" ]; then
        for ps in `ps -ww -eo pid,cmd | grep -v grep | grep -w ${SCRIPT_PATH}/mod_backup.sh | awk '{print $1}'`
        do
            kill -9 $ps
        done
    elif [ $1 == "start" ]; then
        ${SCRIPT_PATH}/mod_backup.sh &
        mod_backup_pid=`ps -ww -eo pid,cmd | grep -v grep | grep -w ${SCRIPT_PATH}/mod_backup.sh | awk '{print $1}' | tail -n1`
        logger_Info "start mod process pid:$mod_backup_pid"
    fi
}

exec_log_retate_process(){
    if [ $1 == "stop" ]; then
        for ps in `ps -ww -eo pid,cmd | grep -v grep | grep -w ${SCRIPT_PATH}/mdw_log_retate_by_size.sh | awk '{print $1}'`
        do
            kill -9 $ps
        done
    elif [ $1 == "start" ]; then
        ${SCRIPT_PATH}/mdw_log_retate_by_size.sh &
        logtrace_pid=`ps -ww -eo pid,cmd | grep -v grep | grep -w ${SCRIPT_PATH}/mdw_log_retate_by_size.sh | awk '{print $1}' | tail -n1`
        logger_Info "start logtrace process pid:$logtrace_pid"
    fi
}

exec_edge_core_script(){
    if [ $1 == "stop" ]; then
        sudo pkill -9 -f ${ATLASEDGE_CORE_BIN}
    elif [ $1 == "start" ]; then
        #通过脚本执行edgecore程序
        sudo -E ${SCRIPT_PATH}/core_install.sh
        ret=$?
        edgecore_pid=`ps -ww -eo pid,cmd | grep -v grep | grep -w ${ATLASEDGE_CORE_BIN} | awk '{print $1}' | tail -n1`
        logger_Info "start ret:$ret edgecore_pid process pid:$edgecore_pid"
    fi
}

exec_postern_process(){
    if [ $1 == "stop" ]; then
        sudo pkill -9 -f ${ATLASEDGE_SITE_BIN}
    elif [ $1 == "start" ]; then
        #执行site程序
        LOG_PATH=`ReadINIfile ${ATLASEDGE_CONFIG_FILE} SYS log_path`
        sudo -b ${PYTHON3} ${ATLASEDGE_SITE_BIN} >> ${LOG_PATH}/atlas_site.log 2>&1
        retry_count=20
        for ((i = 0; i < retry_count; i++)); do
            atlas_site_pids=$(ps -ww -eo pid,cmd | grep -v grep |grep -w postern_main.py | wc -l)
            if [ $atlas_site_pids -lt 2 ]; then
                sleep 0.1
            else
                break
            fi
        done
        sudo pkill -9 -f "${SUDO_ATLASEDGE_SITE_BIN}"
        ret=$?
        postern_pid=`ps -ww -eo pid,cmd | grep -v grep | grep -v sudo |grep -w postern_main.py | awk '{print $1}' | tail -n1`
        logger_Info "start postern ret:$ret process pid:$postern_pid"
    fi
}

# config file resume
exec_configfile_resume()
{
    sudo ${SCRIPT_PATH}/config_resume.sh
}

process_watchdog_loop(){
    export PYTHONPATH=$PYTHONPATH:${WORK_PATH}/software/edge_site/
    # set netmanager ip
    NetmanagerIP=`ReadINIfile ${ATLASEDGE_CONFIG_FILE} SYS net_manager_address`
    if [ "${NetmanagerIP}" !=  "" ]; then
        sudo ${PYTHON3} ${SITE_PYTHON_PATH}/FDIpProc.py
    fi
    check_cert
    exec_configfile_resume

    update_edge_core_config_file

    exec_mod_backup_process stop
    exec_ha_status_monitor stop
    exec_log_retate_process stop
    exec_edge_core_script stop
    exec_postern_process stop

    exec_mod_backup_process start
    exec_ha_status_monitor start
    exec_log_retate_process start
    exec_edge_core_script start
    exec_postern_process start

    logger_Info "edgecore:"$edgecore_pid "postern_pid:" $postern_pid "log trace:" $logtrace_pid "modback:$mod_backup_pid" "ha_monitor:$ha_monitor_pid"

    while true
    do
        sleep $ATLASEDGE_WATCHDOG_SECOND

        if ! [ -n "$ha_monitor_pid" -a -e /proc/$ha_monitor_pid ]; then
            logger_Warn "ha monitor process $ha_monitor_pid not exists restart"
            exec_ha_status_monitor start
        fi

        if ! [ -n "$mod_backup_pid" -a -e /proc/$mod_backup_pid ]; then
            logger_Warn "mod_backup_pid process $mod_backup_pid not exists restart"
            exec_mod_backup_process start
        fi

        if ! [ -n "$logtrace_pid" -a -e /proc/$logtrace_pid ]; then
            logger_Warn "logtrace_pid process $logtrace_pid not exists restart"
            exec_log_retate_process start
        fi

        cat "${ATLASEDGE_CONFIG_PATH}/NODE_INFO" | grep net_manager | grep IEF >/dev/null
        if [ $? -ne 0 ];then
            if ! [ -n "$edgecore_pid" -a -e /proc/$edgecore_pid ]; then
                logger_Warn "edgecore_pid process $edgecore_pid not exists restart"
                exec_edge_core_script start
            fi
        fi

        if ! [ -n "$postern_pid" -a -e /proc/$postern_pid ]; then
            logger_Warn "postern_pid process $postern_pid not exists restart"
            exec_postern_process start
        fi
    done
}

# check CA cert
check_cert(){
    logger_Info "check cert file exist"
    if [ -e ${WORK_PATH}/software/edge_core/certFD/FD.crt ]; then
        update_cert
    fi
}

# update FD CA cert
update_cert(){
    if [ -e /etc/redhat-release ] && [ ! -e /etc/lsb-release ]; then
        if [ ! -e /etc/pki/ca-trust/source/anchors/FD.crt ]; then
            sudo cp -f ${WORK_PATH}/software/edge_core/certFD/FD.crt /etc/pki/ca-trust/source/anchors/
            sudo sha256sum /etc/pki/ca-trust/source/anchors/FD.crt | sudo tee ${WORK_PATH}/software/edge_core/certFD/FD_Work.checksum
            sudo chmod 400 /etc/pki/ca-trust/source/anchors/FD.crt
            sudo update-ca-trust extract
        fi
    else
        if [ ! -e /usr/local/share/ca-certificates/FD.crt ]; then
            sudo cp -f ${WORK_PATH}/software/edge_core/certFD/FD.crt /usr/local/share/ca-certificates/
            sudo sha256sum /usr/local/share/ca-certificates/FD.crt | sudo tee ${WORK_PATH}/software/edge_core/certFD/FD_Work.checksum
            sudo chmod 400 /usr/local/share/ca-certificates/FD.crt
            sudo update-ca-certificates
        fi
    fi

    if [ -e /usr/bin/docker ]; then
        sudo /bin/systemctl restart docker.service
    fi
}

function update_edge_core_config_file()
{
    crl_path_key="crlFile"
    default_crl_path="/etc/pki/tls/fd.crl"
    crl_path_config="\ \ \ \ \ \ \ \ $crl_path_key: $default_crl_path"

    grep $crl_path_key ${WORK_PATH}/${CORE_CONFIG_FILE} > /dev/null 2>&1
    if [ "$?" -ne 0 ]; then
        logger_Info "add core config file item $crl_path_key"
        sudo sed -i "/tlsCaFile:/a $crl_path_config" ${WORK_PATH}/${CORE_CONFIG_FILE}
    else
        logger_Info "core config file already has $crl_path_key"
    fi

    local old_port="8883"
    local new_port="8886"
    grep $old_port ${WORK_PATH}/${CORE_CONFIG_FILE}
    if [ $? -eq 0 ]; then
        logger_Info "update mqttServerInternal port number"
        sudo sed -i "/mqttServerInternal/{s/$old_port/$new_port/;}" ${WORK_PATH}/${CORE_CONFIG_FILE}
    fi
    grep -q brd_t=sei /proc/cmdline 2>/dev/null
    if [[ $? == 0 ]]; then
        logger_Info "begin update_serial_num"
        update_serial_num ${WORK_PATH}/${CORE_CONFIG_FILE}
    fi
}

# exit func
function exit_trap()
{
    trap - INT TERM EXIT QUIT ABRT
    logger_Info "edge main exit pid: $$"
    exec_edge_core_script stop
    kill -9 -$$ > /dev/null 2>&1
    kill -- -$$ > /dev/null 2>&1
}

function edge_upgrade_effect() {
    if [ ! -f ${WORK_PATH}/edge_upd_effect.sh ]; then
        cp -f ${WORK_PATH}/edge_upgrade/software/edge_site/edge_manager/src/script/edge_upd_effect.sh ${WORK_PATH}
    fi
    sudo ${WORK_PATH}/edge_upd_effect.sh
    ret=$?
    logger_Info "check upgrade and effect result:$ret"
    return $ret
}

function edge_processed_launch() {
    restart_service_if_user_changed
    # 设置基准环境变量和链接
    set_bin_path_environment
    # 根据实际更改productName和node_type
    set_product_name
    # A500设备需要能力集替换和开启容器特权校验总开关
    check_A500_and_set_capability
    # start and monitor edge processes
    process_watchdog_loop
}

function set_product_name(){
    check_command_exist dmidecode
    dmidecode_exist=$?
    if [[ ${dmidecode_exist} == 0 ]]; then
        dmi_result="`sudo dmidecode -t1`"
        ProductName=`echo "${dmi_result}" | grep "Product Name:" | sed 's/^.*Product Name:[ \t]//'`
        if [[ "${ProductName}" !=  "" ]]; then
            DEFAULT_PRODUCT_TYPE=${ProductName}
            DEFAULT_PRODUCT_NAME=${ProductName}
        else
            # Atlas200 and Atlas500 not support dmidecode command,
            # determine the Atlas 500 through find "brd_t=sei" in /proc/cmdline
            grep -q brd_t=sei /proc/cmdline 2>/dev/null
            if [[ $? == 0 ]]; then
                DEFAULT_PRODUCT_TYPE="Atlas 500"
                # Atlas 500 have to distinguish "Atlas 500 Model 3010" and "Atlas 500 Model 3000"
                # find "board_id=0x41" in /run/board_cfg.ini
                board_cfg_result="`sudo grep board_id /run/board_cfg.ini 2>/dev/null`"
                atlas_500_id=`echo "${board_cfg_result}" | awk -F '=' '{print $2}'`
                if [[ "${atlas_500_id}" == "0x41" ]]; then
                    DEFAULT_PRODUCT_NAME="Atlas 500 Model 3010"
                elif [[ "${atlas_500_id}" == "0x40" ]]; then
                    DEFAULT_PRODUCT_NAME="Atlas 500 Model 3000"
                else
                    DEFAULT_PRODUCT_NAME="Atlas 500"
                fi
            fi
        fi

        # 先判断NODE_INFO备份文件是否存在
        if [[ -f ${WORK_PATH}/config/backup/NODE_INFO ]]; then
            # 由于该操作在升级过程中的备份恢复之前，需要手动将NODE_INFO文件修改node_type并恢复到正常使用目录中
            # 先从NODE_INFO文件中读取node_type，判断是否与当前获取的node_type相同, 相同则跳过，不同才修改
            node_type=`grep node_type ${WORK_PATH}/config/backup/NODE_INFO 2>/dev/null | awk -F ': ' '{print $2}'`
            if [[ "${DEFAULT_PRODUCT_TYPE}" != "${node_type}" ]]; then
                logger_Info "rewrite the node_type"
                # 修改config下的NODE_INFO中的node_type，兼容老版本升级的情况
                sudo sed -i "s|node_type:.*|node_type: ${DEFAULT_PRODUCT_TYPE}|g" ${WORK_PATH}/config/backup/NODE_INFO 2>/dev/null
                # 2、修改后将备份文件中的edgecore.yaml复制到正常使用目录中
                sudo dd if=${WORK_PATH}/config/backup/NODE_INFO of=${WORK_PATH}/config/NODE_INFO conv=fsync status=none 2>/dev/null
                # 3、修改后需要把备份的NODE_INFO文件删除掉，使其从原文件重新备份
                sudo rm -f ${WORK_PATH}/config/backup/NODE_INFO 2>/dev/null
                sudo rm -f ${WORK_PATH}/config/backup/NODE_INFO.md5 2>/dev/null
                sudo rm -f ${WORK_PATH}/config/backup/NODE_INFO.checksum 2>/dev/null
            fi
        else
            # 如果备份文件不存在，则直接修改源文件
            sudo sed -i "s|node_type:.*|node_type: ${DEFAULT_PRODUCT_TYPE}|g" ${WORK_PATH}/config/NODE_INFO 2>/dev/null
        fi

        # 先判断edgecore.yaml的备份文件是否存在
        if [[ -f ${WORK_PATH}/config/backup/edgecore.yaml ]];then
            # 由于该操作在升级过程中的备份恢复之前，需要手动将edgecore.yaml文件修改productName并恢复到正常使用目录中
            # 先从edgecore.yaml文件中读取productName，判断是否与当前获取的productName相同, 相同则跳过，不同才修改
            product_name=`grep productName ${WORK_PATH}/config/backup/edgecore.yaml 2>/dev/null | awk -F ': ' '{print $2}'`
            if [[ "${DEFAULT_PRODUCT_NAME}" != "${product_name}" ]]; then
                logger_Info "rewrite the productName"
                # 1、先修改备份文件中的edgecore.yaml中的productName
                sudo sed -i "s|productName:.*|productName: ${DEFAULT_PRODUCT_NAME}|g" ${WORK_PATH}/config/backup/edgecore.yaml 2>/dev/null
                # 2、修改后将备份文件中的edgecore.yaml复制到正常使用目录中
                sudo dd if=${WORK_PATH}/config/backup/edgecore.yaml of=${WORK_PATH}/${CORE_CONFIG_FILE} conv=fsync status=none 2>/dev/null
                # 3、修改后需要把备份的edgecore.yaml文件删除掉，使其从原文件重新备份
                sudo rm -f ${WORK_PATH}/config/backup/edgecore.yaml 2>/dev/null
                sudo rm -f ${WORK_PATH}/config/backup/edgecore.yaml.md5 2>/dev/null
                sudo rm -f ${WORK_PATH}/config/backup/edgecore.yaml.checksum 2>/dev/null
            fi
        else
            # 备份文件不存在，直接修改源文件
            sudo sed -i "s|productName:.*|productName: ${DEFAULT_PRODUCT_NAME}|g" ${WORK_PATH}/${CORE_CONFIG_FILE} 2>/dev/null
        fi
    fi
}

function check_A500_and_set_capability(){
    # 500设备进行能力集替换和开启容器特权校验总开关
    grep -q brd_t=sei /proc/cmdline 2>/dev/null
    if [[ $? == 0 ]]; then
        logger_Info "copy A500_capability and set useSecurity is true"
        sudo cp -f ${WORK_PATH}/software/edge_site/edge_manager/config/A500_capability.json ${WORK_PATH}/software/edge_site/edge_manager/config/default_capability.json
        sudo sed -i 's|"useSecuritySetting".*|"useSecuritySetting":true,|g' ${WORK_PATH}/software/edge_core/conf/podconfig.json
        # A500 need set ascend-dmi tool soft link in /usr/local/bin/
        sudo ln -sf /home/data/Ascend-DMI/bin/ascend-dmi /usr/local/bin/ascend-dmi
        # A500 need to set the soft link of the ascend-dmi lib library in /usr/lib64/
        sudo ln -sf /home/data/Ascend-DMI/lib64/libascend_dmi.so /usr/lib64/libascend_dmi.so
        sudo mkdir -p /usr/local/Ascend/
        sudo ln -sf /home/data/miniD/driver/device/opp /usr/local/Ascend/
    fi
}

function restart_service_if_user_changed()
{
    grep -q brd_t=sei /proc/cmdline 2> /dev/null
    if [[ $? -ne 0 ]]; then
        logger_Info "check service user"
        local old_user=$(id -nu $(systemctl show -p UID --value atlasedge.service) 2> /dev/null)
        local new_user=$(grep -Po 'User=\K.*' ${WORK_PATH}/software/edge_site/edge_manager/config/atlasedge.service)
        if [[ "${old_user}" != "${new_user}" ]]; then
            logger_Info "user changed, old user $old_user, new user $new_user, restart service"
            bash ${SCRIPT_PATH}/start.sh restart
            ret=$?
            logger_Warn "restart service ret: $ret"
        fi
    fi
}

function check_running_user()
{
    grep -q brd_t=sei /proc/cmdline 2> /dev/null
    if [ $? -eq 0 ]; then
        if [ "$(whoami)" == "root" ]; then
            sudoer_cmd="HwHiAiUser ALL=(root) NOPASSWD: ${WORK_PATH}/edge_upd_effect.sh"
            grep -q "$sudoer_cmd" /etc/sudoers
            if [ $? -ne 0 ]; then
                echo "$sudoer_cmd" >> /etc/sudoers
            fi
            logger_Info "$(whoami) start atlasEdge with HwHiAiUser"
            sudo -u HwHiAiUser setsid ${WORK_PATH}/edge_main.sh "$@" &
            return $ret_invalid_user
        else
            logger_Info "$(whoami) wait parent process exit"
            retry_count=10
            for ((i = 0; i < retry_count; i++)); do
                edge_main_pid=$(ps -ww -eo pid,cmd | grep -v grep | grep -w ${WORK_PATH}/edge_main.sh | wc -l)
                if [ $edge_main_pid -gt 2 ]; then
                    sleep 0.2
                else
                    break
                fi
            done
            logger_Info "check finished, iteration $i"
        fi
    fi
    return $ret_ok
}

main() {
    trap exit_trap INT TERM EXIT QUIT ABRT
    logger_Info "edge main begin pid: $$ ars:$# arg1:$1"

    check_running_user "$@"
    ret=$?
    if [ "$ret" -ne "$ret_ok" ]; then
        logger_Warn "Warning: atlasEdge running with invalid user"
        return $ret
    fi

    # check edge_main is running or upgrade effecting is running
    checkEdgeIsRunning "$@"
    ret=$?
    if [ $ret -ne 0 ]; then
        logger_Warn "Warning: atlasEdge has been running already. exit"
        return $ret
    fi

    edge_upgrade_effect
    ret=$?
    # case---edge_main.sh is called for upgrade, just return upgrade result
    if  [ $# == 1 -a "$1" == "upgrade" ]; then
        return $ret
    # case---upgrade ok need return and restart edge
    elif [ $ret -eq ${ret_upgrade_ok_need_restart} ]; then
        return ${ret_ok}
    # case---effect finish restart or need back resume or upgrade/effect fail
    elif [ $ret -ne ${ret_ok} ]; then
        return $ret
    fi

    edge_processed_launch
    return $?
}

main "$@"
RESULT=$?
exit $RESULT
